# @Time    :2025/4/10 15:32
def binary_search(alist, item):
    """二分查找，也叫折半查找,递归查找,产生新的列表"""
    n = len(alist)
    if n > 0:
        mid = n // 2
        if alist[mid] == item:
            return True
        elif alist[mid] > item:
            return binary_search(alist[:mid], item)
        else:
            return binary_search(alist[mid + 1:], item)
    return False


def binary_search_2(alist, item):
    """二分查找,非递归查找，是在原有的列表上进行操作"""
    n = len(alist)
    first = 0
    last = n - 1
    while first <= last:
        mid = (first + last) // 2
        if alist[mid] == item:
            return True
        elif alist[mid] > item:
            last = mid - 1
        else:
            first = mid + 1
    return False


if __name__ == '__main__':
    alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(binary_search(alist, 15))
    print(binary_search(alist, 1))
    print(binary_search_2(alist, 9))
    print(binary_search_2(alist, 10))
